import {getNow} from "../utils/utils.js";
import {config} from "../config/index.js";
import {Op} from "sequelize";
import db from "../models/index.js";

let captcha = db.captcha;
let captchaDao = {

};

// 新增验证码
captchaDao.add = (user_id, code, type, t) => {
  code = (code + "").toUpperCase();
  let deadline = getNow() + config.CAPTCHA_DEADLINE;
  if(!t) {
    return captcha.create({user_id, code, type, deadline});
  }
  return captcha.create({user_id, code, type, deadline,}, {transaction: t});
};

// 验证用户的某一类型的验证码是否正确 带事务
captchaDao.verify = async (user_id, type, code, t) => {
  code = (code + "").toUpperCase();
  let result = await captcha.count(
    {
      where: {user_id, type, code, deadline: {[Op.gt]: getNow()}},
      transaction: t
    }
  );
  return result > 0;
};

// 删除用户的某一类型的验证码
captchaDao.delete = (user_id, type, t) => {
  if(!t) {
    return captcha.destroy(
      {where: {user_id, type}}
    );
  }
  return captcha.destroy(
    {
      where: {user_id, type},
      transaction: t
    }
  );
};

// 更新数据库该类型的验证码 以及最后时间
captchaDao.updateOrCreate = async (user_id, type, code, t) => {
  code = (code + "").toUpperCase();
  let deadline = getNow() + config.CAPTCHA_DEADLINE;
  let count = await captcha.count({where: {user_id, type}});
  let isExist = count > 0;
  if (!t) {
    if(isExist) {
      return captcha.update({code, deadline}, {where: {user_id, type}});
    }
    return captcha.create({code, deadline, type, user_id});
  }
  if(isExist) {
    return captcha.update({code, deadline}, {where: {user_id, type}, transaction: t});
  }
  return captcha.create({code, deadline, type, user_id}, {transaction: t});
};

export default captchaDao;
